package com.winshare.saleAssistant.controller;

import com.alibaba.excel.EasyExcel;
import com.aliyun.oss.OSSException;
import com.winshare.saleAssistant.domain.dto.req.DataAnalysisQueryDTO;
import com.winshare.saleAssistant.domain.dto.req.FileDTO;
import com.winshare.saleAssistant.domain.dto.req.StaffExcelExportDTO;
import com.winshare.saleAssistant.domain.dto.resp.StaffExcelExportData;
import com.winshare.saleAssistant.domain.dto.resp.analys.ProductSaleAnalysisResp;
import com.winshare.saleAssistant.domain.entity.ProductInfoDO;
import com.winshare.saleAssistant.domain.query.ProductInfoQuery;
import com.winshare.saleAssistant.exception.BusinessException;
import com.winshare.saleAssistant.model.*;
import com.winshare.saleAssistant.modelVo.LoginCountVo;
import com.winshare.saleAssistant.modelVo.LoginTotal;
import com.winshare.saleAssistant.modelVo.ProductCoverSchool;
import com.winshare.saleAssistant.service.*;
import com.winshare.saleAssistant.util.*;
import com.winshare.saleAssistant.util.SecurityManager;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 销售数据分析
 *
 * @author whz
 */
@Controller
@RequestMapping("/sys/saleDataAnalysis")
@Api(tags = "销售数据分析页面接口")
public class SaleDataAnalysisController {

    @Resource
    ISaleService saleService;

    @Resource
    private ISchoolService schoolService;

    @Resource
    ITUserService userService;

    @Resource
    IUserLoginLogService userLoginLogService;

    @Autowired
    ProductInfoService productInfoService;

    @Autowired
    IUserOperationLogService userOperationLogService;

    @Autowired
    private IDataStaticService dataStaticService;
    @Autowired
    private FileService fileService;

    @RequestMapping("/getSaleDetail")
    @ResponseBody
    @ApiOperation(value = "获取销售概览", notes = ",", httpMethod = "POST")
    public Object getDetail(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) {
        ProductSaleAnalysisResp resp = new ProductSaleAnalysisResp();
        try {
            Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
            Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
            //销售总额
            String num = saleService.getSell(starTime, endTime, dataAnalysisQueryDTO.productName);
            resp.setSaleTotalAmount(num);

            //产品销售数量
            Integer num1 = saleService.getPSellCount(starTime, endTime, dataAnalysisQueryDTO.productName);
            resp.setSaleTotalNum(num1);

            //产品覆盖城市数量和区域数量
            Integer num2 = schoolService.getCTotal(starTime, endTime, dataAnalysisQueryDTO.productName);
            resp.setSaleCityNum(num2);

            Integer num3 = schoolService.getATotal(starTime, endTime, dataAnalysisQueryDTO.productName);
            resp.setSaleAreaNum(num3);

            //产品覆盖学校数量
            Integer num4 = schoolService.getSchoolCount(starTime, endTime);
            resp.setSaleSchoolNum(num4);

            //服务用户数量
            Integer num5 = userService.getTUserCount(starTime, endTime, dataAnalysisQueryDTO.productName);
            resp.setSaleUserNum(num5);

            //用户使用次数
            int num6 = userLoginLogService.getTUserLogCount(starTime, endTime, dataAnalysisQueryDTO.productName);
            resp.setSaleUserUseNum(num6);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return LogicResponse.success(resp);

    }


    /**
     * 产品销售趋势
     *
     * @return
     */
    @RequestMapping("/getSaleTotal")
    @ResponseBody
    @ApiOperation(value = "产品销售趋势", notes = ",", httpMethod = "POST")
    public Object getSaleTotal(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) {
        ProductInfoQuery query = new ProductInfoQuery();
        if (ToolUtil.isNotEmpty(dataAnalysisQueryDTO.getProductName())) {
            query.setProductName(dataAnalysisQueryDTO.getProductName());
        }
        List<ProductInfoDO> products = productInfoService.getProducts(query);
        List<Map<String, Object>> productList = BeanMapUtils.objectsToMaps(BeanMapUtils.toObject(products));
        List<String> time = new ArrayList<>();
        List<String> name = new ArrayList<>();
        for (Map<String, Object> map : productList) {
            name.add(map.get("productName").toString());
            if (dataAnalysisQueryDTO.sjType.equals("1")) {
                List<Map<String, Object>> saleMap = saleService.getSaleTotalMonth(Integer.parseInt(map.get("id").toString()));
                if (time.size() == 0) {
                    time.add("一月");
                    time.add("二月");
                    time.add("三月");
                    time.add("四月");
                    time.add("五月");
                    time.add("六月");
                    time.add("七月");
                    time.add("八月");
                    time.add("九月");
                    time.add("十月");
                    time.add("十一月");
                    time.add("十二月");
                }
                map.put("total", saleMap);
            } else if (dataAnalysisQueryDTO.sjType.equals("2")) {
                List<Map<String, Object>> saleMap = saleService.getSaleTotalWeek(Integer.parseInt(map.get("id").toString()));
                if (time.size() == 0) {
                    time.add("周日");
                    time.add("周一");
                    time.add("周二");
                    time.add("周三");
                    time.add("周四");
                    time.add("周五");
                    time.add("周六");
                }
                map.put("total", saleMap);
            } else {
                List<Map<String, Object>> saleMap = saleService.getSaleTotalYear(Integer.parseInt(map.get("id").toString()));
                for (Map<String, Object> map1 : saleMap) {
                    if (!time.contains(map1.get("time").toString())) {
                        time.add(map1.get("time").toString());
                    }
                }
                map.put("total", saleMap);
            }
        }
        List<Map<String, Object>> list = new ArrayList<>();
        for (Map<String, Object> map : productList) {
            Map<String, Object> m = new HashMap<>();
            m.put("name", map.get("productName").toString());
            m.put("type", "line");
            m.put("stack", "总量");
            List<Integer> num = new ArrayList<>();
            List<Map<String, Object>> saleMap = (List<Map<String, Object>>) map.get("total");
            for (String str : time) {
                Integer number = 0;
                for (Map<String, Object> map1 : saleMap) {
                    if (dataAnalysisQueryDTO.sjType.equals("0")) {
                        if (str.equals(map1.get("time").toString())) {
                            number = Integer.parseInt(map1.get("pTotal").toString());
                        }
                    } else {
                        number = Integer.parseInt(map1.get(str).toString());
                    }
                }
                num.add(number);
            }
            m.put("data", num);
            list.add(m);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("time", time);
        map.put("list", list);
        return LogicResponse.success(map);
    }

    /**
     * 产品登录折线图
     *
     * @return
     */
    @RequestMapping("/getProduct")
    @ResponseBody
    @ApiOperation(value = "产品登录折线图", notes = ",", httpMethod = "POST")
    public Object getProduct(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) {
        List<ProductInfoDO> products = productInfoService.getProducts(null);
        List<Map<String, Object>> productList = BeanMapUtils.objectsToMaps(BeanMapUtils.toObject(products));
        List<String> time = new ArrayList<>();
        List<String> name = new ArrayList<>();
        for (Map<String, Object> map : productList) {
            name.add(map.get("productName").toString());
            if (dataAnalysisQueryDTO.sjType.equals("1")) {
                List<Map<String, Object>> saleMap = saleService.getLoginTotalMonth(Integer.parseInt(map.get("id").toString()));
                if (time.size() == 0) {
                    time.add("一月");
                    time.add("二月");
                    time.add("三月");
                    time.add("四月");
                    time.add("五月");
                    time.add("六月");
                    time.add("七月");
                    time.add("八月");
                    time.add("九月");
                    time.add("十月");
                    time.add("十一月");
                    time.add("十二月");
                }
                map.put("total", saleMap);
            } else if (dataAnalysisQueryDTO.sjType.equals("2")) {
                List<Map<String, Object>> saleMap = saleService.getLoginTotalWeek(Integer.parseInt(map.get("id").toString()));
                if (time.size() == 0) {
                    time.add("周日");
                    time.add("周一");
                    time.add("周二");
                    time.add("周三");
                    time.add("周四");
                    time.add("周五");
                    time.add("周六");
                }
                map.put("total", saleMap);
            } else {
                List<Map<String, Object>> saleMap = saleService.getLoginTotalYear(Integer.parseInt(map.get("id").toString()));
                for (Map<String, Object> map1 : saleMap) {
                    if (!time.contains(map1.get("time").toString())) {
                        time.add(map1.get("time").toString());
                    }
                }
                map.put("total", saleMap);
            }
        }
        List<Map<String, Object>> list = new ArrayList<>();
        for (Map<String, Object> map : productList) {
            Map<String, Object> m = new HashMap<>();
            m.put("name", map.get("productName").toString());
            m.put("type", "line");
            m.put("stack", "总量");
            List<Integer> num = new ArrayList<>();
            List<Map<String, Object>> saleMap = (List<Map<String, Object>>) map.get("total");
            for (String str : time) {
                Integer number = 0;
                for (Map<String, Object> map1 : saleMap) {
                    if (dataAnalysisQueryDTO.sjType.equals("0")) {
                        if (str.equals(map1.get("time").toString())) {
                            number = Integer.parseInt(map1.get("pTotal").toString());
                        }
                    } else {
                        number = Integer.parseInt(map1.get(str).toString());
                    }
                }
                num.add(number);
            }
            m.put("data", num);
            list.add(m);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("name", name);
        map.put("time", time);
        map.put("list", list);
        return LogicResponse.success(map);
    }

    /**
     * 销售产品构成
     */
    @RequestMapping("/getSaleProduct")
    @ResponseBody
    @ApiOperation(value = "销售产品构成", notes = ",", httpMethod = "POST")
    public Object getSale(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        List<Map<String, Object>> saleProduct = saleService.getSaleProduct(starTime, endTime);
        return LogicResponse.success(saleProduct);
    }

    /**
     * 销售区域分布
     */
    @RequestMapping("/getSaleArea")
    @ResponseBody
    @ApiOperation(value = "销售区域分布", notes = ",", httpMethod = "POST")
    public Object getSaleArea(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        List<Map<String, Object>> SaleArea = saleService.getSaleArea(starTime, endTime);
        return LogicResponse.success(SaleArea);
    }

    /**
     * 销售明细
     * 产品名称
     */
    @RequestMapping("/getSalesDetail")
    @ResponseBody
    @ApiOperation(value = "销售明细", notes = "产品名称", httpMethod = "POST")
    public Object salesDetail(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        //销售总额
        Map<String, Object> map = new HashMap<>();

        String num = saleService.getSell(starTime, endTime, dataAnalysisQueryDTO.productName);
        map.put("productMoeny", num);

        //产品销售数量
        Integer num1 = saleService.getPSellCount(starTime, endTime, dataAnalysisQueryDTO.productName);
        map.put("saleNumber", num1);

        //产品覆盖城市数量和区域数量
        Integer num2 = schoolService.getCTotal(starTime, endTime, dataAnalysisQueryDTO.productName);
        Integer num3 = schoolService.getATotal(starTime, endTime, dataAnalysisQueryDTO.productName);
        map.put("productCity", num2);
        map.put("productArea", num3);

        //产品覆盖学校数量
        Integer num4 = schoolService.getSchoolCount1(starTime, endTime, dataAnalysisQueryDTO.productName);
        map.put("num4", num4);

        //服务用户数量
        Integer num5 = userService.getTUserCount(starTime, endTime, dataAnalysisQueryDTO.productName);
        map.put("userUserTotal", num5);


        //用户使用次数
        int num6 = userLoginLogService.getTUserLogCount(starTime, endTime, dataAnalysisQueryDTO.productName);
        map.put("productSchool", num6);

        return LogicResponse.success(map);
    }

    @RequestMapping("getSaleCMStatistical")
    @ResponseBody
    @ApiOperation(value = "产品版本销售情况", notes = "", httpMethod = "POST")
    public Object getSaleCMStatistical(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        return LogicResponse.success(saleService.getSaleCMStatistical(dataAnalysisQueryDTO.productName, starTime, endTime));
    }

    /**
     * 销售情况排名 销售金额
     */
    @RequestMapping("/getrankingMoney")
    @ResponseBody
    @ApiOperation(value = "销售城市排名", notes = "销售金额", httpMethod = "POST")
    public Object getrankingMoney(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        List<Sale> sales = saleService.getrankingMoney(dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.parentAreaName, dataAnalysisQueryDTO.cityName, dataAnalysisQueryDTO.productName, starTime, endTime);
        return LogicResponse.success(sales);
    }

    /**
     * 销售情况排名 按销售数量
     */
    @RequestMapping("/getrankingTotal")
    @ResponseBody
    @ApiOperation(value = "销售情况排名", notes = "按销售数量", httpMethod = "POST")
    public Object getrankingTotal(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        List<Sale> sales = saleService.getrankingTotal(dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.parentAreaName, dataAnalysisQueryDTO.cityName, dataAnalysisQueryDTO.productName, starTime, endTime);
        return LogicResponse.success(sales);
    }

    /**
     * 获取区县销售排名
     */
    @RequestMapping("/getAreaSaleRanking")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cityName", value = "市州名称", required = false),
            @ApiImplicitParam(name = "productName", value = "产品名称", required = false),
            @ApiImplicitParam(name = "orderBy", value = "排序方式(ProductTotal-按销量,productMoney-按金额", required = true),
            @ApiImplicitParam(name = "startTimeInfo", value = "起始时间字符串", required = false),
            @ApiImplicitParam(name = "endTimeInfo", value = "结束时间字符串", required = false),
    })
    @ApiOperation(value = "获取区县销售排名", notes = "按销售数量", httpMethod = "POST")
    public Object getAreaSaleRanking(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        dataAnalysisQueryDTO.setStarTime(getStartTime(dataAnalysisQueryDTO.startTimeInfo));
        dataAnalysisQueryDTO.setEndTime(getEndTime(dataAnalysisQueryDTO.endTimeInfo));
        return LogicResponse.success(saleService.getAreaSaleRanking(dataAnalysisQueryDTO));
    }


    /**
     * 产品数量
     *
     * @return
     */
    @RequestMapping("/getProductTotal")
    @ResponseBody
    @ApiOperation(value = "产品覆盖学校数量", notes = "", httpMethod = "POST")
    public Object getProductTotal(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        Integer productTotal = saleService.getProductTotal(dataAnalysisQueryDTO.parentAreaName, dataAnalysisQueryDTO.productName, starTime, endTime);
        return LogicResponse.success(productTotal);
    }

    /**
     * 产品数量
     *
     * @return
     */
    @RequestMapping("/getTeacherTotal")
    @ResponseBody
    @ApiOperation(value = "老师使用数量", notes = "", httpMethod = "POST")
    public Object getTeacherTotal(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        Integer productTotal = saleService.getTeacherTotal(dataAnalysisQueryDTO.parentAreaName, dataAnalysisQueryDTO.productName, starTime, endTime);
        return LogicResponse.success(productTotal);
    }

    /**
     * 产品数量
     *
     * @return
     */
    @RequestMapping("/getStudentTotal")
    @ResponseBody
    @ApiOperation(value = "学生使用数量", notes = "", httpMethod = "POST")
    public Object getStudentTotal(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        Integer productTotal = saleService.getStudentTotal(dataAnalysisQueryDTO.parentAreaName, dataAnalysisQueryDTO.productName, starTime, endTime);
        return LogicResponse.success(productTotal);
    }

    @RequestMapping("/getUserSchoolUseList")
    @ResponseBody
    @ApiOperation(value = "使用学校数据", notes = "", httpMethod = "POST")
    public Object getUserSchoolUseList(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        return LogicResponse.success(saleService.getUserSchoolUseList(dataAnalysisQueryDTO.schoolId));
    }

    @RequestMapping("/getRateOfCoverage")
    @ResponseBody
    @ApiOperation(value = "产品覆盖学校", notes = "", httpMethod = "POST")
    public Object getRateOfCoverage(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        List<Sale> rateOfCoverage = saleService.getRateOfCoverage(dataAnalysisQueryDTO.parentAreaName, dataAnalysisQueryDTO.productName, starTime, endTime);
        List<ProductCoverSchool> list = new ArrayList<>();
        if (!rateOfCoverage.isEmpty()) {
            for (int i = 0; i < rateOfCoverage.size(); i++) {
                ProductCoverSchool productCoverSchool = new ProductCoverSchool();
                productCoverSchool.setSchoolCoverTotal(rateOfCoverage.get(i).getProductTotal());
                productCoverSchool.setCityName(rateOfCoverage.get(i).getAreaName());
                Integer citySchoolTotal = saleService.getCitySchoolTotal(rateOfCoverage.get(i).getAreaName());
                productCoverSchool.setSchoolTotal(citySchoolTotal);
                productCoverSchool.setCover((rateOfCoverage.get(i).getProductTotal() / citySchoolTotal * 100) + "%");
                list.add(productCoverSchool);
            }
        }
        return LogicResponse.success(list);
    }

    /**
     * 区域使用排名 按登录次数
     */
    @RequestMapping("/getAreaLogin")
    @ResponseBody
    @ApiOperation(value = "区域使用排名", notes = "按登录次数", httpMethod = "POST")
    public Object getAreaLogin(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        List<Sale> loginTotal = saleService.getLoginTotal(dataAnalysisQueryDTO.parentAreaName, dataAnalysisQueryDTO.productName, starTime, endTime);
        return LogicResponse.success(loginTotal);
    }

    /**
     * 区域使用排名 按使用次数
     */
    @RequestMapping("/getLogin")
    @ResponseBody
    @ApiOperation(value = "区域使用排名", notes = "按使用次数", httpMethod = "POST")
    public Object getLogin(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        List<Sale> login = saleService.getLogin(dataAnalysisQueryDTO.parentAreaName, dataAnalysisQueryDTO.productName, starTime, endTime);
        return LogicResponse.success(login);
    }

    /**
     * 产品使用排名
     */
    @RequestMapping("/getProductEmploy")
    @ResponseBody
    @ApiOperation(value = "产品使用排名", notes = "", httpMethod = "POST")
    public Object getProductEmploy(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        List<Sale> productEmploy = saleService.getProductEmploy(dataAnalysisQueryDTO.parentAreaName, dataAnalysisQueryDTO.productName, starTime, endTime);
        return LogicResponse.success(productEmploy);
    }


    /**
     * excel导出
     */

//    @RequestMapping(value = "/export")
//    @ResponseBody
//    public void export(HttpServletResponse response) throws Exception {
//        try {
//            Date date = new Date();
//            DateFormat format = new SimpleDateFormat("yyyyMMdd");
//            String time = format.format(date);
//
//            Page<Map<String, Object>> page = new PageFactory<Map<String, Object>>().defaultPage1();
//            if (page != null) {
//                List<Map<String, Object>> list = saleService.getExportSale(page);
//                String[] title = new String[]{"区域", "学校编号", "学校简称", "购买产品"};
//                //excel文件名
//                String fileName = "产品覆盖信息表" + time + ".xls";
//                //sheet名
//                String sheetName = "产品覆盖信息表";
//                String[][] content = null;
//                if (list != null) {
//                    content = new String[list.size()][];
//                    for (int i = 0; i < list.size(); i++) {
//
//                        content[i] = new String[title.length];
//                        content[i][0] = list.get(i).get("cityName").toString();
//                        content[i][1] = list.get(i).get("schoolCode").toString();
//                        if (list.get(i).get("school_name") == null || list.get(i).get("school_name") == "") {
//                            content[i][2] = "NULL";
//                        } else {
//                            content[i][2] = list.get(i).get("school_name").toString();
//                        }
//                        if (list.get(i).get("productName") == null || list.get(i).get("productName") == "") {
//                            content[i][3] = "NULL";
//                        } else {
//                            content[i][3] = list.get(i).get("productName").toString();
//                        }
//                    }
//                }
//                //创建HSSFWorkbook 　　　　　　
//                HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
//                // 响应到客户端
//                this.setResponseHeader(response, fileName);
//                OutputStream os = response.getOutputStream();
//                wb.write(os);
//                os.flush();
//                os.close();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//
//        }
//    }
    private void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 学科比列
     */
    @RequestMapping("/getSubjectCount")
    @ResponseBody
    @ApiOperation(value = "学科比列", notes = "", httpMethod = "POST")
    public Object getSubjectCount(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        return LogicResponse.success(userService.getSubjectCount(dataAnalysisQueryDTO.provinceName,
                dataAnalysisQueryDTO.cityName, dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.productName,
                starTime, endTime));
    }

    /**
     * 学段比列
     */
    @RequestMapping("/getLearSectionCount")
    @ResponseBody
    @ApiOperation(value = "学段比列", notes = "", httpMethod = "POST")
    public Object getLearSectionCount(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        return LogicResponse.success(userService.getLearSectionCount(dataAnalysisQueryDTO.provinceName,
                dataAnalysisQueryDTO.cityName, dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.productName,
                starTime, endTime));
    }


    /**
     * 功能使用时长排名
     */
    @RequestMapping("/getFunTime")
    @ResponseBody
    @ApiOperation(value = "功能使用时长排名", notes = "", httpMethod = "POST")
    public Object getFunTime(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        List<UserOperationLog> funCount = userOperationLogService.getFunTime(dataAnalysisQueryDTO.provinceName,
                dataAnalysisQueryDTO.cityName, dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.productName,
                starTime, endTime,
                dataAnalysisQueryDTO.orderBy);
        return LogicResponse.success(funCount);
    }

    /**
     * 功能使用次数排名
     */
    @RequestMapping("/getFunCount")
    @ResponseBody
    @ApiOperation(value = "功能使用次数排名", notes = "", httpMethod = "POST")
    public Object getFunCount(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        List<UserOperationLog> funCount = userOperationLogService.getFunCount(dataAnalysisQueryDTO.provinceName,
                dataAnalysisQueryDTO.cityName, dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.productName,
                starTime, endTime,
                dataAnalysisQueryDTO.orderBy);
        return LogicResponse.success(funCount);
    }

    /**
     * 男女比列
     */
    @RequestMapping("/getSexProportion")
    @ResponseBody
    @ApiOperation(value = "男女比列", notes = "", httpMethod = "POST")
    public Object getSexProportion(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        List<LoginCountVo> sexProportion = userService.getSexProportion(dataAnalysisQueryDTO.provinceName,
                dataAnalysisQueryDTO.cityName, dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.productName,
                starTime, endTime);
        return LogicResponse.success(sexProportion);
    }

    /**
     * 年龄段
     */
    @RequestMapping("/getPopAge")
    @ResponseBody
    @ApiOperation(value = "年龄段", notes = "", httpMethod = "POST")
    public Object getPopAge(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        Map<String, Object> popAge = userService.getPopAge(dataAnalysisQueryDTO.provinceName,
                dataAnalysisQueryDTO.cityName, dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.productName,
                starTime, endTime);
        return LogicResponse.success(popAge);
    }


    /**
     * 功能使用次数和时长
     */
    @RequestMapping("/getFunTimeCount")
    @ResponseBody
    @ApiOperation(value = "功能使用次数和时长", notes = "", httpMethod = "POST")
    public Object getFunTimeCount(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        dataAnalysisQueryDTO.setStarTime(getStartTime(dataAnalysisQueryDTO.startTimeInfo));
        dataAnalysisQueryDTO.setEndTime(getEndTime(dataAnalysisQueryDTO.endTimeInfo));
        List<UserOperationLog> funTimeCount = userOperationLogService.getFunTimeCount(dataAnalysisQueryDTO);
        return LogicResponse.success(funTimeCount);
    }

    @RequestMapping("/getSchoolCountTime")
    @ResponseBody
    @ApiOperation(value = "学校使用时间", notes = "", httpMethod = "POST")
    public Object getSchoolCountTime(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        List<UserLoginLog> schoolCountTime = userLoginLogService.getSchoolCountTime(dataAnalysisQueryDTO.provinceName,
                dataAnalysisQueryDTO.cityName, dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.productName,
                starTime, endTime,
                dataAnalysisQueryDTO.orderBy);
        return LogicResponse.success(schoolCountTime);
    }


    /**
     * 学校详情页面 用户使用排名
     */
    @RequestMapping("/getUserCountTime")
    @ResponseBody
    @ApiOperation(value = "学校详情页面", notes = "用户使用排名", httpMethod = "POST")
    public Object getUserCountTime(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        List<TUser> list = userService.getUserCountTime(dataAnalysisQueryDTO.orderBy,
                dataAnalysisQueryDTO.schoolName, dataAnalysisQueryDTO.provinceName, dataAnalysisQueryDTO.cityName,
                dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.productName,
                starTime, endTime);
        return LogicResponse.success(list);
    }

    /**
     * 县 市 登录次数 时间 激活率排名
     */
    @RequestMapping("/getPALogin")
    @ResponseBody
    @ApiOperation(value = "登录次数", notes = "时间 激活率排名", httpMethod = "POST")
    public Object getPALogin(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        List<Map<String, Object>> list = userLoginLogService.getPALogin(dataAnalysisQueryDTO.productName, starTime, endTime, dataAnalysisQueryDTO.orderBy);
        return LogicResponse.success(list);
    }

    /**
     * 获取开始时间
     *
     * @param startTimeInfo
     * @return
     * @throws Exception
     */
    private Date getStartTime(String startTimeInfo) throws Exception {
        SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String starTime1 = "2021-01-01 00:00:00";
        if (ToolUtil.isNotEmpty(startTimeInfo)) {
            starTime1 = startTimeInfo + " 00:00:00";
        }
        return sm.parse(starTime1);
    }

    /**
     * 获取结束时间
     *
     * @param endTimeInfo
     * @return
     * @throws Exception
     */
    private Date getEndTime(String endTimeInfo) throws Exception {
        SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sm.format(new Date());
        if (ToolUtil.isNotEmpty(endTimeInfo)) {
            format = endTimeInfo + " 23:59:59";
        }
        return sm.parse(format);
    }


    /**
     * 各时段登录次数折线图
     */
    @RequestMapping("/getloginDiscount")
    @ResponseBody
    @ApiOperation(value = "各时段登录次数折线图", notes = "", httpMethod = "POST")
    public Object getloginDiscount(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        Map<String, Object> map = userLoginLogService.getloginDiscount(dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.productName, starTime, endTime);
        return LogicResponse.success(map);
    }

    /**
     * 高频使用时间段
     */
    @RequestMapping("/getHighTime")
    @ResponseBody
    @ApiOperation(value = "高频使用时间段", notes = "", httpMethod = "POST")
    public Object getHighTime(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        List<UserLoginLog> highTime = userLoginLogService.getHighTime(dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.productName, starTime, endTime);
        return LogicResponse.success(highTime);
    }


    /**
     * 人均使用时长
     */
    @RequestMapping("/getPerTime")
    @ResponseBody
    @ApiOperation(value = "人均使用时长", notes = "", httpMethod = "POST")
    public Object getPerTime(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        int days = (int) ((endTime.getTime() - starTime.getTime()) / (1000 * 3600 * 24));
        //计算需要查询的天数
        //查询所有的使用时长
        int perTime = userOperationLogService.getPerTime(dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.productName, starTime, endTime);
        //查询所有使用人数
        int accountTotal = userService.getAccountTotal(dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.productName, starTime, endTime);
        float time = (float) perTime / accountTotal / days;
        DecimalFormat df = new DecimalFormat("0.0");
        String format = df.format(time);
        return LogicResponse.success(format);
    }

    /**
     * 人均登录次数
     */
    @RequestMapping("/getLoginTotal")
    @ResponseBody
    @ApiOperation(value = "人均登录次数", notes = "", httpMethod = "POST")
    public Object getLoginTotal(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        int days = (int) ((endTime.getTime() - starTime.getTime()) / (1000 * 3600 * 24));
        //计算需要查询的天数
        LoginTotal lt = new LoginTotal();
        //查出账号总数
        List<TUser> list = userService.getActivationTotal(dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.productName, starTime, endTime);
        //查出登录次数
        int loginTotal = userLoginLogService.getLoginLogTotatol(dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.productName, starTime, endTime);
        if (!list.isEmpty()) {
            TUser tUser = list.get(0);
            int total = (tUser.getActivateTotal());
            int daysTotal = loginTotal > 0 && days > 0 ? loginTotal / days : 0;

            //设置人均日登录次数
            int perLoginTotal = daysTotal > 0 && total > 0 ? loginTotal / days / total : 0;
            lt.setLoginTotal(perLoginTotal);

            //设置日均登录次数
            lt.setLoginDayTatol(daysTotal);
        }
        return LogicResponse.success(lt);
    }

    /**
     * 账号激活概率
     */
    @RequestMapping("/getPercent")
    @ResponseBody
    @ApiOperation(value = "账号激活概率", notes = "", httpMethod = "POST")
    public Object getPercent(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        List<TUser> activationTotal = userService.getActivationTotal(dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.productName, starTime, endTime);
        return LogicResponse.success(activationTotal);
    }

    /**
     * 导出
     *
     * @return
     */
//    @RequestMapping(value = "/excel")
//    @ResponseBody
//    public Object excel(HttpServletResponse response, HttpServletRequest request, String areaName) {
//        List<Map<String, Object>> list = saleService.getExportList(areaName);
//        try {
//            String fileName = "产品覆盖" + System.currentTimeMillis() + ".xls"; // 文件名
//            String sheetName = "产品覆盖";// sheet名
//            Map<String, Object> object = null;
//            String[] title = new String[]{"区域", "学校编号", "学校名称", "购买产品"};// 标题
//            String[][] values = new String[list.size()][];
//            for (int i = 0; i < list.size(); i++) {
//                values[i] = new String[title.length];
//                // 将对象内容转换成string
//                object = list.get(i);
//                //order.getType()==1?"所有用户":"用户"+order.getUserId();
//                values[i][0] = (String) object.get("area_name");
//                values[i][1] = (String) object.get("school_code");
//                values[i][2] = (String) object.get("school_name");
//                values[i][3] = (String) object.get("saleName");
//            }
//            HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
//
//            this.setResponseHeader(response, fileName);
//            OutputStream os = response.getOutputStream();
//            wb.write(os);
//            os.flush();
//            os.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return SUCCESS_TIP;
//    }
    @RequestMapping("/getRegionalSituation")
    @ResponseBody
    @ApiOperation(value = "区域情况统计", notes = "", httpMethod = "POST")
    public Object getRegionalSituation(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        return LogicResponse.success(saleService.getRegionalSituation(dataAnalysisQueryDTO.productName, starTime, endTime));
    }

    @RequestMapping("/getLoginTime")
    @ResponseBody
    @ApiOperation(value = "登录次数数据", notes = "", httpMethod = "POST")
    public Object getLoginTime(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        List<Map<String, Object>> loginList = saleService.getLoginTime(dataAnalysisQueryDTO.productName, starTime, endTime);
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> m = new HashMap<>();
        m.put("name", "次数");
        m.put("type", "line");
        m.put("stack", "登陆次数");
        List<Integer> num = new ArrayList<>();
        List<String> time = new ArrayList<>();
        for (Map<String, Object> map : loginList) {
            num.add(Integer.parseInt(map.get("num").toString()));
            time.add(map.get("startTime") + "-" + map.get("endTime"));
        }
        m.put("data", num);
        list.add(m);
        Map<String, Object> map = new HashMap<>();
        map.put("time", time);
        map.put("list", list);
        return LogicResponse.success(map);
    }


    /**
     * 产品数量
     *
     * @return
     */
    @RequestMapping("/getTeaAndStuTotal")
    @ResponseBody
    @ApiOperation(value = "产品覆盖-获取覆盖教师和学生数量", notes = ",", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentAreaName", value = "区域名称", required = false),
            @ApiImplicitParam(name = "productName", value = "产品名称", required = false),
    })
    public Object getTeaAndStuTotal(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        Map<String, Object> result = new HashMap<>();
        Integer teacherTotal = saleService.getTeacherTotal(dataAnalysisQueryDTO.parentAreaName, dataAnalysisQueryDTO.productName, starTime, endTime);
        Integer studentTotal = saleService.getStudentTotal(dataAnalysisQueryDTO.parentAreaName, dataAnalysisQueryDTO.productName, starTime, endTime);
        result.put("teacherTotal", teacherTotal);
        result.put("studentTotal", studentTotal);
        return LogicResponse.success(result);
    }

    /**
     * @return
     * @throws Exception
     */
    @RequestMapping("/getSchoolUseList")
    @ResponseBody
    @ApiOperation(value = "学校使用情况排名", notes = "", httpMethod = "POST")
    public Object getSchoolUseList(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        //根据产品名称查询销售数量,销售金额,发布时间
        return LogicResponse.success(saleService.getSchoolUseList(dataAnalysisQueryDTO.orderBy, dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.productName, starTime, endTime));
    }

    /**
     * 用户使用排名
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/getUserUseList")
    @ResponseBody
    @ApiOperation(value = "用户使用情况排名", notes = "", httpMethod = "POST")
    public Object getUserUseList(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        //根据产品名称查询销售数量,销售金额,发布时间
        return LogicResponse.success(saleService.getUserUseList(dataAnalysisQueryDTO.orderBy, dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.productName, starTime, endTime));
    }

    /**
     * 功能使用排名
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/getFunUseList")
    @ResponseBody
    @ApiOperation(value = "功能使用情况排名", notes = "", httpMethod = "POST")
    public Object getFunUseList(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        //根据产品名称查询销售数量,销售金额,发布时间
        return LogicResponse.success(saleService.getFunUseList(dataAnalysisQueryDTO.orderBy, dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.productName, starTime, endTime));
    }

    /**
     * 模块使用时长排行
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/getModularUseTime")
    @ResponseBody
    @ApiOperation(value = "模块使用时长排行", notes = "", httpMethod = "POST")
    public Object getModularUseTime(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        //根据产品名称查询销售数量,销售金额,发布时间
        return LogicResponse.success(dataStaticService.getModularUseTime(starTime, endTime, dataAnalysisQueryDTO.productName, dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.orderBy, dataAnalysisQueryDTO.productCode));
    }

    /**
     * 功能使用次数排行
     *
     * @return
     * @throws Exception
     */
    @RequestMapping("/getFunUseNum")
    @ResponseBody
    @ApiOperation(value = "功能使用次数排行", notes = "", httpMethod = "POST")
    public Object getFunUseNum(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        //根据产品名称查询销售数量,销售金额,发布时间
        return LogicResponse.success(dataStaticService.getFunUseNum(starTime, endTime, dataAnalysisQueryDTO.productName, dataAnalysisQueryDTO.areaName, dataAnalysisQueryDTO.orderBy));
    }

    @RequestMapping("/getTotal")
    @ResponseBody
    @ApiOperation(value = "未知", notes = "", httpMethod = "POST")
    public Object getTotal(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        //根据产品名称查询销售数量,销售金额,发布时间
        Map<String, Object> map = dataStaticService.getTotal(starTime, endTime, dataAnalysisQueryDTO.productName, dataAnalysisQueryDTO.areaName);
        if (map == null) {
            map = new HashMap<>();
            map.put("maxTime", "");
            map.put("maxNum", "0");
        }
        Map<String, Object> map1 = dataStaticService.getTotal1(starTime, endTime, dataAnalysisQueryDTO.productName, dataAnalysisQueryDTO.areaName);
        if (map1 == null) {
            map.put("minTime", "");
            map.put("minNum", "0");
        } else {
            map.put("minTime", map1.get("minTime"));
            map.put("minNum", map1.get("minNum"));
        }
        Map<String, Object> map2 = dataStaticService.getTotal2(starTime, endTime, dataAnalysisQueryDTO.productName, dataAnalysisQueryDTO.areaName);
        if (map2 == null) {
            map.put("maxUseTime", "");
            map.put("maxUseNum", "0");
        } else {
            map.put("maxUseTime", map2.get("maxUseTime"));
            map.put("maxUseNum", map2.get("maxUseNum"));
        }
        Map<String, Object> map3 = dataStaticService.getTotal3(starTime, endTime, dataAnalysisQueryDTO.productName, dataAnalysisQueryDTO.areaName);
        if (map3 == null) {
            map.put("minUseTime", "");
            map.put("minUseNum", "0");
        } else {
            map.put("minUseTime", map3.get("minUseTime"));
            map.put("minUseNum", map3.get("minUseNum"));
        }
        Map<String, Object> map4 = dataStaticService.getTotal4(starTime, endTime, dataAnalysisQueryDTO.productName, dataAnalysisQueryDTO.areaName);
        if (map4 == null) {
            map.put("avgDay", "0");
        } else {
            map.put("avgDay", map4.get("avgDay"));
        }
        return LogicResponse.success(map);
    }

    @RequestMapping("/getUserSexTotal")
    @ResponseBody
    @ApiOperation(value = "获取用户性别统计", notes = "", httpMethod = "POST")
    public Object getUserSexTotal(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        Date starTime = getStartTime(dataAnalysisQueryDTO.startTimeInfo);
        Date endTime = getEndTime(dataAnalysisQueryDTO.endTimeInfo);
        //根据产品名称查询销售数量,销售金额,发布时间
        return LogicResponse.success(dataStaticService.getUserSexTotal(starTime, endTime, dataAnalysisQueryDTO.productName, dataAnalysisQueryDTO.areaName));
    }

    @RequestMapping("/getUserAge")
    @ResponseBody
    @ApiOperation(value = "获取用户年龄统计", notes = "", httpMethod = "POST")
    public Object getUserAge(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        dataAnalysisQueryDTO.setStarTime(getStartTime(dataAnalysisQueryDTO.startTimeInfo));
        dataAnalysisQueryDTO.setEndTime(getEndTime(dataAnalysisQueryDTO.endTimeInfo));
        return LogicResponse.success(dataStaticService.getUserAge(dataAnalysisQueryDTO.starTime, dataAnalysisQueryDTO.endTime, dataAnalysisQueryDTO.productName, dataAnalysisQueryDTO.areaName));
    }

    @RequestMapping("/queryCityRanking")
    @ResponseBody
    @ApiOperation(value = "获取城市排名", notes = "", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productCode", value = "产品编号", required = false),
            @ApiImplicitParam(name = "productName", value = "产品编号名称", required = false),
            @ApiImplicitParam(name = "orderBy", value = "排序方式(loginTotal-登录次数,useTime-使用时长,activationRate-激活率", required = true),
            @ApiImplicitParam(name = "startTimeInfo", value = "起始时间字符串", required = false),
            @ApiImplicitParam(name = "endTimeInfo", value = "结束时间字符串", required = false),
    })
    public Object getCityRanking(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        dataAnalysisQueryDTO.setStarTime(getStartTime(dataAnalysisQueryDTO.startTimeInfo));
        dataAnalysisQueryDTO.setEndTime(getEndTime(dataAnalysisQueryDTO.endTimeInfo));
        return LogicResponse.success(dataStaticService.getCityRanking(dataAnalysisQueryDTO));
    }

    @RequestMapping("/queryAreaRanking")
    @ResponseBody
    @ApiOperation(value = "获取区县排名", notes = "", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productCode", value = "产品编号", required = false),
            @ApiImplicitParam(name = "productName", value = "产品编号名称", required = false),
            @ApiImplicitParam(name = "orderBy", value = "排序方式(loginTotal-登录次数,useTime-使用时长,activationRate-激活率", required = true),
            @ApiImplicitParam(name = "startTimeInfo", value = "起始时间字符串", required = false),
            @ApiImplicitParam(name = "endTimeInfo", value = "结束时间字符串", required = false),
    })
    public Object getAreaRanking(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        dataAnalysisQueryDTO.setStarTime(getStartTime(dataAnalysisQueryDTO.startTimeInfo));
        dataAnalysisQueryDTO.setEndTime(getEndTime(dataAnalysisQueryDTO.endTimeInfo));
        return LogicResponse.success(dataStaticService.getAreaRanking(dataAnalysisQueryDTO));
    }

    @RequestMapping("/queryParentAreaRanking")
    @ResponseBody
    @ApiOperation(value = "获取区域排名", notes = "", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productCode", value = "产品编号", required = false),
            @ApiImplicitParam(name = "productName", value = "产品编号名称", required = false),
            @ApiImplicitParam(name = "orderBy", value = "排序方式(employ-功能使用次数,loginTotal-登录次数", required = true),
            @ApiImplicitParam(name = "startTimeInfo", value = "起始时间字符串", required = false),
            @ApiImplicitParam(name = "endTimeInfo", value = "结束时间字符串", required = false),
    })
    public Object getParentAreaRanking(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        dataAnalysisQueryDTO.setStarTime(getStartTime(dataAnalysisQueryDTO.startTimeInfo));
        dataAnalysisQueryDTO.setEndTime(getEndTime(dataAnalysisQueryDTO.endTimeInfo));
        return LogicResponse.success(dataStaticService.getParentAreaRanking(dataAnalysisQueryDTO));
    }

    @RequestMapping("/querySchoolRanking")
    @ResponseBody
    @ApiOperation(value = "获取学校排名(分页)", notes = "", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productCode", value = "产品编号", required = false),
            @ApiImplicitParam(name = "productName", value = "产品编号名称", required = false),
            @ApiImplicitParam(name = "cityName", value = "市区名称", required = false),
            @ApiImplicitParam(name = "orderBy", value = "排序方式(loginTotal-登录次数,useTime-使用时长,activationRate-激活率", required = true),
            @ApiImplicitParam(name = "startTimeInfo", value = "起始时间字符串", required = false),
            @ApiImplicitParam(name = "endTimeInfo", value = "结束时间字符串", required = false),
            @ApiImplicitParam(name = "pageSize", value = "每页数量，建议10-20", required = true),
            @ApiImplicitParam(name = "pageIndex", value = "第几页，从1开始", required = true),
    })
    public Object getSchoolRanking(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        dataAnalysisQueryDTO.setStarTime(getStartTime(dataAnalysisQueryDTO.startTimeInfo));
        dataAnalysisQueryDTO.setEndTime(getEndTime(dataAnalysisQueryDTO.endTimeInfo));
        return LogicResponse.success(dataStaticService.getSchoolRanking(dataAnalysisQueryDTO));
    }

    @RequestMapping("/queryUserRanking")
    @ResponseBody
    @ApiOperation(value = "获取用户排名(分页)", notes = "", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productCode", value = "产品编号", required = false),
            @ApiImplicitParam(name = "productName", value = "产品编号名称", required = false),
            @ApiImplicitParam(name = "schoolCode", value = "学校编号", required = false),
            @ApiImplicitParam(name = "orderBy", value = "排序方式(loginTotal-登录次数,useTime-使用时长,activationRate-激活率", required = true),
            @ApiImplicitParam(name = "startTimeInfo", value = "起始时间字符串", required = false),
            @ApiImplicitParam(name = "endTimeInfo", value = "结束时间字符串", required = false),
            @ApiImplicitParam(name = "pageSize", value = "每页数量，建议10-20", required = true),
            @ApiImplicitParam(name = "pageIndex", value = "第几页，从1开始", required = true),
    })
    public Object getUserRanking(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) throws Exception {
        dataAnalysisQueryDTO.setStarTime(getStartTime(dataAnalysisQueryDTO.startTimeInfo));
        dataAnalysisQueryDTO.setEndTime(getEndTime(dataAnalysisQueryDTO.endTimeInfo));
        return LogicResponse.success(dataStaticService.getUserRanking(dataAnalysisQueryDTO));
    }

    @PostMapping("/download")
    @ResponseBody
    @ApiOperation(value = "导出学校覆盖详细excel文件,返回一个文件下载链接，自行下载", notes = "导出学校覆盖详细excel文件,返回一个文件下载链接，自行下载")
    public Object download(@RequestBody DataAnalysisQueryDTO dataAnalysisQueryDTO) {
        String fileName = "School" + System.currentTimeMillis() + ".xlsx";
        List<SchoolRankingModel> schoolRankingList = dataStaticService.getSchoolRankingList(dataAnalysisQueryDTO);
        EasyExcel.write(fileName, SchoolRankingModel.class).sheet("School").doWrite(schoolRankingList);
        FileDTO fileDTO = new FileDTO();
        try {
            fileDTO.setFileContent(SecurityManager.entryptBase64(Files.readAllBytes(Paths.get(fileName))));
            String randomFileName = UUID.randomUUID().toString().replace("-", "").substring(0, 5);
            fileDTO.setFileName(randomFileName + ".xlsx");
            String upload = fileService.upload(fileDTO);
            return LogicResponse.success(Optional.ofNullable(upload).orElse(null));
        } catch (IOException | OSSException e) {
            throw new BusinessException(e.getMessage());
        } finally {
            try {
                Files.deleteIfExists(Paths.get(fileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
